import * as THREE from '../../build/three.module.js';
import Stats from '../../jsm/libs/stats.module.js';

const scene = new THREE.Scene();
scene.background = new THREE.Color( 0x050505 );
scene.fog = new THREE.Fog( 0x050505, 2000, 3500 );

const camera = new THREE.PerspectiveCamera(27, innerWidth / innerHeight, 1, 3500);
camera.position.z = 2750;

const gmt = new THREE.BufferGeometry();
const particles = 500000;

const positions = [];
const colors = [];

const color = new THREE.Color();
const n = 1000, n2 = n / 2;

for(let i = 0; i < particles; i += 1) {
  const x = Math.random() * n - n2;
  const y = Math.random() * n - n2;
  const z = Math.random() * n - n2;

  positions.push(x, y, z);

  const vx = (x / n) + .5;
  const vy = (y / n) + .5;
  const vz = (z / n) + .5;

  color.setRGB(vx, vy, vz);

  colors.push(color.r, color.g, color.b);
}

gmt.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
gmt.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
gmt.computeBoundingSphere();

const mtl = new THREE.PointsMaterial({
  size: 15,
  vertexColors: THREE.VertexColors
});

const points = new THREE.Points(gmt, mtl);
scene.add(points)

const renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const stats = new Stats();
document.body.appendChild(stats.dom);

renderer.setAnimationLoop(() => {

  const time = Date.now() * .001;
  points.rotation.x = time * .25;
  points.rotation.y = time * .5;

  renderer.render(scene, camera);
  stats.update();

})

const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatirx();

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize, false);